<?php
date_default_timezone_set("Asia/Shanghai");
$toDay= date("Ymd",time());
$surplus = 20;
require_once 'class/phpqrcode.php';
require_once 'class/ip.php';
$i = new ip();
$ip = $i->ipAddress();
if ($ip=='null'){
    echo json_encode(array('code'=>'11','state'=>'error','details'=>'非法IP'),JSON_UNESCAPED_UNICODE);
    return;
}

$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$frequency = md5($toDay.$ip);
$fredis = $redis->exists($frequency);
if ($fredis==0){
    $redis->set($frequency,'1');
    $redis->expire($frequency,'3600');
    qrcodess($surplus-1);
}else{
    $fredis2 = $redis->get($frequency);
    if ($fredis2>=$surplus){
        echo json_encode(array('code'=>'22','state'=>'error','details'=>'当前次数上限,请等待一个小时'),JSON_UNESCAPED_UNICODE);
        return;
    }
    $Num = $redis->get($frequency);
    $timess = $redis->ttl($frequency);
    $redis->set($frequency,$Num+1);
    $redis->expire($frequency,$timess);
    $timess = $redis->ttl($frequency);
    qrcodess($surplus-$Num-1);
}

function qrcodess($num){
    $value = $_GET['text'];
    $level= 'L';
    $size = 8;

    ob_start();
    QRcode::png($value,false,  $level,$size,2);
    $img = ob_get_contents();//获取缓冲区内容
    ob_end_clean();//清除缓冲区内容
    $imgInfoBase64 = 'data:image/png;base64,'.str_replace(array("\r\n", "\r", "\n"), '',chunk_split(base64_encode($img)));//转base64      清除base64中的换行符
    $imgInfo = str_replace(array("\r\n", "\r", "\n"), '',chunk_split(base64_encode($img)));
    ob_flush();
    if ($value==''){
        echo json_encode(array('code'=>'33','state'=>'error','details'=>'缺少参数'),JSON_UNESCAPED_UNICODE);
        return;
    }
    echo str_replace("\\/", "/", json_encode(array('QrCode'=>$imgInfo,'QrCodeBase64'=>$imgInfoBase64,'surplus'=>$num,'code'=>'1','state'=>'success'),JSON_UNESCAPED_UNICODE));
}

?>
